package com.benmei.weike.web;

import com.benmei.weike.common.Constants;
import com.benmei.weike.common.Lang;
import com.benmei.weike.dto.*;
import com.benmei.weike.dto.IntoClassRoom.IntoClassRoomRequest;
import com.benmei.weike.dto.IntoClassRoom.IntoClassRoomResponse;
import com.benmei.weike.dto.LeaveClassRoom.LeaveClassRoomRequest;
import com.benmei.weike.entity.Appointment;
import com.benmei.weike.entity.ReserveTime;
import com.benmei.weike.entity.TeacherAppointmentTime;
import com.benmei.weike.entity.reserve.ScheduleList;
import com.benmei.weike.exception.ClientException;
import com.benmei.weike.exception.ServerException;
import com.benmei.weike.service.AppointmentService;
import com.benmei.weike.service.common.MemcachedService;
import com.benmei.weike.util.JsonUtil;
import com.nativetalk.base.RetInfo;
import com.nativetalk.bean.member.TdNtMember;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * Created by Peter on 2017/9/6.
 */
@RestController
@RequestMapping(value = "/v4.3.1/student/appointment")
public class AppointmentStudentController {
    public static final Logger logger = LoggerFactory.getLogger(AppointmentStudentController.class);

    @Autowired
    private MemcachedService memcachedService;

    @Autowired
    private AppointmentService appointmentService;

    @RequestMapping(value = "/token/add", method = {RequestMethod.POST}, consumes = "application/json")
    public RetInfo addAppointment(@RequestBody Appointment appointment,
                                  @RequestHeader(value = "token", required = false) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(appointment));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            // 发布版本时在校验，这个版本先不校验时区参数，如果不传时区，默认使用服务器的时区
            String clientTimeZoneId = appointment.getClientTimeZoneId();
            // 校验时区是否为空
            if (StringUtils.isEmpty(clientTimeZoneId)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("TimeZone must not be empty");
                logger.error("时区id不能为空 clientTimeZoneId：" + clientTimeZoneId);
                return retInfo;
            }
            // 校验时区是否有效
            TimeZone clientTimeZone = TimeZone.getTimeZone(clientTimeZoneId);
            if (clientTimeZone == null) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Invalid TimeZone");
                logger.error("时区无效clientTimeZoneId：" + clientTimeZoneId);
                return retInfo;
            }

            appointment.setMemb_id(tdNtMember.getMemb_id());
            List<ScheduleList> scheduleLists = appointmentService.studentAppointTeacher(appointment, tdNtMember, clientTimeZone);
            Map map = new HashMap();
            map.put("weekReservetime", scheduleLists);
            RetInfo retInfo = RetInfo.getSuccessInfo("成功");
            retInfo.setObj(map);
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    @RequestMapping(value = "/otherPlatform/add", method = {RequestMethod.POST}, consumes = "application/json")
    public RetInfo otherPlatformAppointment(@RequestBody OtherPlatformAppointmentDto otherPlatformAppointmentDto) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(otherPlatformAppointmentDto));
            appointmentService.otherPlatformAppointment(otherPlatformAppointmentDto);
            RetInfo retInfo = RetInfo.getSuccessInfo("成功");
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getCode(), e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }



    @RequestMapping(value = "/token/intoClassRoom", method = {RequestMethod.POST}, consumes = "application/json")
    public RetInfo studentIntoClassRoom(@RequestBody IntoClassRoomRequest request,
                                        @RequestHeader(value = "token", required = false) String token, HttpServletRequest httpRequest) {

        String clientType = "";
        try {
            clientType = httpRequest.getHeader("client_type");
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(request));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            IntoClassRoomResponse response = appointmentService.intoClassRoom(request, Constants.UserRole.student, tdNtMember.getMemb_id());
            RetInfo retInfo = RetInfo.getSuccessInfo(response);
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getMessage(), clientType);
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ServerException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo(e.getMessage(), clientType);
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo(RetInfo.ReturnCode.SERVER_ERROR_MSG_CN, clientType);
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    @RequestMapping(value = "/token/leaveClassRoom", method = {RequestMethod.POST}, consumes = "application/json")
    public RetInfo studentLeaveClassRoom(@RequestBody LeaveClassRoomRequest request,
                                         @RequestHeader(value = "token", required = false) String token) {
        try {
            //打印入参
            logger.info(Constants.prefix_in + JsonUtil.toJson(request));

            //校验token，如果校验通过就从缓存中读取Member
            if (StringUtils.isBlank(token)) {
                RetInfo retInfo = RetInfo.getClientErrorInfo("Parameter token  is required");
                logger.info(JsonUtil.toJson(retInfo));
                return retInfo;
            }
            Object o = memcachedService.get(token);
            if (o == null) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存中没有MemberToken:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }

            if (!TdNtMember.class.isInstance(o)) {
                RetInfo retInfo = RetInfo.getReloginInfo(Lang.ZH);
                logger.info("缓存的token不是TdNtMember类型:[" + token + "]，用户需要重新登录系统。 retInfo-->" + JsonUtil.toJson(retInfo));
                return retInfo;
            }
            TdNtMember tdNtMember = (TdNtMember) o;

            appointmentService.leaveClassRoom(request, Constants.UserRole.student, tdNtMember.getMemb_id());
            RetInfo retInfo = RetInfo.getSuccessInfo();
            //打印出参
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ClientException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getClientErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (ServerException e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo(e.getMessage());
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }

    // -------------------- A版后台预约相关接口-------------------------------------------------------------------------------------------------
    // A版后台预约 - 预览 -  查询老师时间块的状态
    @RequestMapping(value = "/admin/preview")
    @ResponseBody
    public AdminAppointmentPreviewResponse appointmentPreviewForA(@RequestBody String body) {
        logger.info(Constants.prefix_in + body);
        AdminAppointmentPreviewResponse response = new AdminAppointmentPreviewResponse();
        try {
            AdminAppointmentPreviewRequest vo = JsonUtil.toObject(body, AdminAppointmentPreviewRequest.class);
            List<TeacherAppointmentTime> list = appointmentService.previewForA(vo);
            response.setTimeList(list);
            logger.info(Constants.prefix_out + JsonUtil.toJson(response));
            return response;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setMark("1");
            response.setTip(e.getMessage());
            logger.error(Constants.prefix_out + JsonUtil.toJson(response));
            return response;
        }
    }

    // A版后台预约 - 保存预约 ->  查询老师时间块的状态
    @RequestMapping(value = "/admin/save/validTimeBlock")
    @ResponseBody
    public ReserveTime appointmentSaveValidTimeBlockForA(@RequestBody String body) {
        logger.info(Constants.prefix_in + body);
        try {
            AdminAppointmentSaveValidTimeBlockRequest vo = JsonUtil.toObject(body, AdminAppointmentSaveValidTimeBlockRequest.class);
            ReserveTime reserveTime = appointmentService.appointmentSaveValidTimeBlockForA(vo);
            logger.info(Constants.prefix_out + JsonUtil.toJson(reserveTime));
            return reserveTime;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            logger.error(Constants.prefix_out);
            return null;
        }
    }

    // A版后台预约 - 保存预约(同步时间块状态)
    @RequestMapping(value = "/admin/save")
    @ResponseBody
    public RetInfo appointmentSaveForA(@RequestBody String body) {
        //打印入参
        logger.info(Constants.prefix_in + body);
        try {
            AdminApointmentSyncTimeBlockRequest vo = JsonUtil.toObject(body, AdminApointmentSyncTimeBlockRequest.class);
            appointmentService.appointmentSaveForA(vo);
            RetInfo retInfo = RetInfo.getSuccessInfo("SUCCESS");
            logger.info(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        } catch (Exception e) {
            //记录错误日志
            RetInfo retInfo = RetInfo.getServerErrorInfo();
            logger.error(e.getMessage(), e);
            //打印出参
            logger.error(Constants.prefix_out + JsonUtil.toJson(retInfo));
            return retInfo;
        }
    }
}
